Before you can start to create a DHTML application, you need to know at least some rudiments of HTML, such as how an HTML page is created and the most important and frequently used HTML tags. If you're already familiar with HTML syntax, you can safely skip this section.
Even though the HTML language has its own logic, it isn't as structured as high-level programming languages such as Visual Basic. For this reason, many programmers find HTML syntax rules somewhat strange. As always, nothing beats hands-on practice, so I prepared a simple editor that lets you write an HTML fragment and immediately see how the browser renders it. I wrote this piece of software using the WebBrowser control, which is nothing less than Internet Explorer embedded in an ActiveX control.
Although this simple editor can't compete with Microsoft FrontPage or even the simplest freeware HTML editor, it does offer some useful features. First, it allows you to swap from the editor to the preview window with the touch of a button (F4 for the editor, F5 for the preview window). Second, it provides several shortcut key combinations that you can use to add the most common HTML tags and even to enter more complex structures such as tables and controls. All these shortcuts are listed in the Insert menu, as shown in Figure 19-1. The source code for this editor is on the companion CD, and you're welcome to improve it to add support for additional HTML tags or other capacities.
Figure 19-1. Two instances of the Cheap DHTML Editor: one in editor mode and one in preview mode.
An HTML page is a file that consists of plain text plus tags that tell the browser how the page should be rendered on the client's screen. This is the skeleton of an HTML page:
<HTML> <HEAD> <TITLE>The title of this page</TITLE> </HEAD> <BODY> Welcome to HTML </BODY> </HTML> |
This code displays the string "Welcome to HTML" near the top border of an otherwise blank page. Notice that all the elements in the page are enclosed within a pair of tags (and each tag is enclosed between angle brackets . For example, the title of the page—the string that Internet Explorer displays in the caption of its main window—is enclosed between the <TITLE> and the </TITLE> tags. The <BODY> and </BODY> tags enclose the text that appears inside the page.
Typically, the body of a page contains one or more headings. HTML supports six different levels of headings, where level 1 corresponds to the most important heading and level 6 to the least important one. Headings are useful for giving subtitles to sections of the page:
<BODY> <H1>This is a level 1 heading</H1> Some normal text here <H2>This is a level 2 heading</H2> Text under level 2 heading </BODY> |
An important characteristic of the HTML language is that carriage return characters and line feed characters in the source text don't affect the appearance of the page. Apart from headings and a few other tags, which add a CR-LF pair automatically, if you want to start a new line, you have to insert a <P> tag manually, as here:
This is a paragraph.<P>As is this.<P> |
The <P> tag forces a new line and also inserts a blank line between the current paragraph and the next one. If you need to break the current line but you don't want an extra blank line, you can use the <BR> tag:
This paragraph is subdivided<BR>into two distinct lines.<P> |
To add a horizontal line of space between two paragraphs, you can also use the <HR> tag:
Two paragraphs separated<HR>by a horizontal line<P> |
The <PRE> and </PRE> pair of tags is an exception to the rule that carriage returns in HTML source text are ignored: Everything between these tags is rendered as monospaced text (typically using the Courier font), and all embedded CR-LF character pairs are inserted in the resulting output. These tags are often used to insert text as is (for example, a source code listing):
<PRE>First line second line</PRE> |
By default, all text is aligned at the left, but you can use the <CENTER> and </CENTER> tags to center a portion of text:
<CENTER>A centered paragraph<P> Another centered paragraph</CENTER> |
NOTE
If you're using the DHTMLed editor, you can center any portion of text by highlighting its source code, pressing Ctrl+T to enter a tag pair, and then typing CENTER in the input box. You can use the same method for any tag pair, such as <PRE> and </PRE>. Other commands in the Insert menu—for example, the Bold, Italic, and Hyperlink commands—automatically add a pair of tags at the beginning and end of the selected text.
Creating lists of bulleted or numbered items is easy in HTML. You create bulleted items by using the <LI> and </LI> tags to mark the beginning and the end of individual items and then enclosing the entire list within <UL> and </UL>:
<UL> <LI>First bulleted paragraph</LI> <LI>Second bulleted paragraph</LI> <LI>Third bulleted paragraph</LI> </UL> |
You create a list of numbered items in much the same way. The only difference is that you must enclose the list within the <OL> and </OL> pair of tags:
<OL> <LI>First you must do this.</LI> <LI>Then you must do that.</LI> </OL> |
Most HTML tags can embed special attributes that affect how the text between the tags is rendered. For example, by default, headings are left-aligned, but you can modify the alignment of a given heading by adding the ALIGN attribute:
<H1 ALIGN=center>This is a centered level 1 heading</H1> <H2 ALIGN=right>This is a right-aligned level 2 heading</H2> |
The TEXT attribute defines the color of the text for a page element. If you use this attribute for the BODY tag, the color affects the entire page:
<BODY BGCOLOR="cyan" TEXT="#FF0000"> Text on this page is red over a cyan background. </BODY> |
You can specify a color attribute using the #RRGGBB format, which is similar to the Visual Basic RGB function, or you can use one of the following 16 color names accepted by Internet Explorer: Black, Maroon, Green, Olive, Navy, Purple, Teal, Gray, Silver, Red, Lime, Yellow, Blue, Fuchsia, Aqua, and White. The BODY tag also supports other color attributes, such as LINK (used for hyperlinks), ALINK (to render active hyperlink), and VLINK (to mark visited hyperlinks).
You can make text boldface by enclosing it within the <B> and </B> pair of tags. Similarly, you can italicize a portion of text with the <I> and </I> pair:
<B>This text is boldface.</B><P> <I>This text is italic.</I><P> <B>This sentence in boldface has an <I>italicized</I> word in it.</B> |
You can use the <U> and </U> tag pair to underline text. This isn't usually a good idea, however, because the underline attribute should be reserved for hyperlinks. You can apply attributes to an entire paragraph by enclosing them between the <P> and </P> tags, as in the following example:
<P ALIGN=center>Centered paragraph</P> |
To modify the attributes of the text, you can use the <FONT> tag, which takes three attributes: FACE, SIZE, and COLOR. The COLOR attribute is specified in the same way as before. The FACE attribute is the name of a font. This attribute even accepts a comma-delimited list of font names if you want to provide alternate choices in case the preferred font isn't available on the user's machine:
<FONT FACE="Arial, Helvetica" SIZE=14 COLOR="red">Red text</FONT> |
This statement attempts to use the Arial font, but it reverts to Helvetica if Arial isn't installed on the user's system. The SIZE attribute is the font size in points. This attribute also accepts a number preceded by a plus or a minus sign to indicate a size relative to the default font size:
Text in regular size<P> <FONT SIZE=+4>Text 4 points taller</FONT><P> <FONT SIZE=-2>Text 2 points smaller</FONT> |
To insert an image in an HTML page, you need the <IMG> tag, whose SRC attribute specifies the path to the image to be displayed; such a path can be absolute or relative to the path of the page itself. For example, the following code loads a GIF image located in the same directory as the HTML source file:
<IMG src="mylogo.gif"> |
Images are typically in GIF or JPEG format. GIF images can be interlaced, in which case the browser first downloads every other line of pixels and then downloads the remaining lines.
As you can for text strings, you can center an image horizontally by enclosing the <IMG> tab within the <CENTER> and </CENTER> tags or by using the ALIGN attribute. If you know the size of the image being downloaded, you can specify it using the WIDTH and HEIGHT attributes so that the browser can correctly position the text around the image before actually downloading it. The image's width and height are expressed in pixels:
This is a right-aligned image 200 pixels wide and 100 pixels high. <IMG ALIGN=right WIDTH=200 HEIGHT=100 src="mylogo.gif"> |
If necessary, the browser will stretch or shrink the original image to fit the size you've specified. This feature is often exploited to insert graphical elements that separate areas on the page. For example, you can create a horizontal separator by using an image with a gradient background and a HEIGHT attribute of just a few pixels.
You can control how much white space is left around the image by using the HSPACE and VSPACE attributes, for horizontal and vertical space, respectively. By default, a 2-pixel transparent border is drawn around all images, but you can suppress it (by setting the BORDER attribute to none) or specify a different width:
A right-aligned image with 10 pixels of horizontal white space and 20 pixels of vertical space <IMG VSPACE=20 ALIGN=right src="mylogo.gif" HSPACE=10> |
Finally, the ALT attribute is used to provide a textual description of the image; this description is displayed in the browser while the image is being downloaded, and it completely replaces the image if the user has turned off images.
HTML supports three different types of hyperlinks: a hyperlink to another location on the same page, a hyperlink to another page on the same server, and a hyperlink to a page in another Internet domain. In all cases, you use the <A> and </A> tags to define which portion of the text will appear to be underlined. These tags are always accompanied by the HREF attribute, which points to the hyperlink's target:
Click <A href="pagetwo.htm">here</a> to proceed to the next page, or click <A href="toc.htm">here</a> to go to the table of contents. |
If the destination of the hyperlink is inside the same page, you need a way to label it. You do this with the <A> tag and the NAME attribute:
<A NAME="Intro">Introduction</A> |
(You don't need to insert a string between the opening and closing tags.) You can place this tag, also known as the anchor, before the first line of the target portion of HTML source code. To refer to an anchor inside the same page, you use the # symbol for the value of the HREF attribute:
Click <A href="#intro">here</a> to go to the introduction. |
(Warning: intra-page hyperlinks aren't supported by the Cheap DHTML editor demo on the CD.) You can have a hyperlink point to an anchor inside another page by using the following syntax:
Click <A href="chap1.htm#intro">here</a> to go to the book's introduction. |
You can also have the hyperlink point to any page on another server by providing the fully qualified URL to it:
Jump to the <A href="http://www.vb2themax.com/index.htm"> VB-2-The-Max</A> Web site. |
You can even use images as hyperlinks. The syntax is the same, and you only have to insert an <IMG> tag instead of plain text inside the <A> and </A> tag pair:
<A href="http://www.vb2themax.com"><img src="mylogo.gif"></a> |
You can create clickable images linked to an image map. In this case, the image includes multiple hot spots, each one pointing to a different target. This advanced technique is beyond the scope of this HTML tutorial, so I won't elaborate on image maps here.
The HTML language has a rich assortment of tags and keywords for creating and formatting tables. Tables are important in plain HTML because they offer a way to precisely position and align text and image elements. All the data pertaining to a table is enclosed between a pair of <TABLE> and </TABLE> tags. Each new row is marked with a <TR> tag, and each column by a <TD> tag. You can also use the <TH> tag for cells in header rows. The </TR>, </TD>, and </TH> closing tags are optional. The following example displays a table with two columns and three rows, the first of which is a header row:
<TABLE BORDER=1> <TR> <TH> HeadRow 1, Column 1</TH> <TH> HeadRow 1, Column 2</TH> </TR><TR> <TD> Row 1, Column 1</TD> <TD> Row 1, Column 2</TD> </TR><TR> <TD> Row 2, Column 1</TD> <TD> Row 2, Column 2</TD> </TR></TABLE> |
The BORDER attribute specifies the border's width; if this attribute is omitted, the table doesn't display a border. You can change the border's color using the BORDERCOLOR attribute, and you can even create a 3-D effect with the BORDERCOLORLIGHT and BORDERCOLORDARK attributes. The table can have a background color (the BGCOLOR attribute), or it can use a background image specified by the BACKGROUND attribute.
Each cell can contain text, an image, or both. You can change the horizontal alignment of the contents of a cell by using the ALIGN attribute (which can take the values left, center, or right), and you can control the vertical alignment with the VALIGN attribute (which can be assigned the values top, middle, or bottom). By default, a cell is wide enough to display its contents, but you can set any size you want with the WIDTH and HEIGHT attributes, whose values are in pixels. For the WIDTH attribute, you can also specify a percentage of the table's width. You can apply most of these attributes to the <TR>, <TD>, and <TH> tags alike. The following example shows how to apply these tags; the result is shown in Figure 19-2:
<TABLE BORDER=1> <TR > <TH HEIGHT=100> A row 100 pixels tall</TH> <TH> <IMG src="mylogo.gif"></th> </TR> <TR> <TD WIDTH=200 HEIGHT= 90 ALIGN=center VALIGN=bottom> Text aligned to center, bottom</TD> <TD WIDTH=50%> This cell takes half of the table's width. </TD> </TR> <TR VALIGN=bottom> <TD> This row is bottom-aligned.</TD> <TD ALIGN=right> This one is right-aligned.</TD> </TR></TABLE> |
A cell can also contain a hyperlink or an image that works as a hyperlink. By default, a table is wide enough to show its contents, but you can use the WIDTH attribute of the <TABLE> tag to specify an absolute width in pixels or a percentage of the window's width:
<TABLE BORDER=1 WIDTH=90%> |
Figure 19-2. A table with an embedded image and different formatting and alignment options.
Styles offer a way to define the appearance of an HTML tag in an HTML page. If you don't specify a style, a given heading is always displayed with its default attributes—for example, a <H1> heading always uses a black New Times Roman font 14 points tall. You can modify this default setting by using a surrounding <FONT> tag, as in this code:
<FONT FACE="Arial" SIZE=20 COLOR="red"><H1>Level 1 Heading</H1></FONT> |
The problem with the preceding approach is that if all your Level 1 headings need to be rendered with nondefault attributes, you must update all the individual occurrences of the <H1> tag. And when you later want to change to another color or font size, you need to revise all the tags once again.
Conversely, if you define and then apply a style you need to redefine the <H1> tag just once, and your change will affect the entire document. You can even take a further step, and keep your style definitions in a separate file—a Cascading Style Sheet file, or CSS—that can be referenced by all the HTML pages that make up your application. This approach gives you an effective way to keep the contents of an HTML document separated from its appearance so that you can easily modify either one of them independently from the other. While it's common practice to keep styles in a separate file, for the sake of clarity in the following examples I'll embed the definition of the style in the HTML page that uses it.
You can define a new style using the <STYLE> and </STYLE> pair of tags. For example, see how you can redefine the <H1> and <H2> tags:
<STYLE> H1 {FONT-FAMILY=Arial; FONT-SIZE=20; COLOR="red"} H2 {FONT-FAMILY=Arial; FONT-SIZE=16; FONT-STYLE=italic; COLOR="green"} </STYLE> <H1>This is a Red heading</H1> <H2>This is a Green italic heading</H2> |
The name of the tag that you want to redefine is followed by a semicolon-delimited list of ATTRIBUTE=value pairs enclosed within braces. In most cases, you can also omit the double quotes that surround a string value, for example, when you're specifying a color attribute. You can redefine as many tags as you want within a single <STYLE> and </STYLE> tag pair.
Style sheets even let you define contextual behaviors. Take, for instance, the definition of the <H2> tag above, which renders all the level 2 headings as green italicized text. Such a style actually nullifies the effect of an <I> tag inside the heading because the text is already italic. You can remedy this by specifying that <I> tags inside a <H2> and </H2> pair should produce normal (nonitalic) characters in the color red. You enforce this behavior by adding this definition to the style (added line is in boldface):
<STYLE> H1 {FONT-FAMILY=Arial; FONT-SIZE=20; COLOR="red"} H2 {FONT-FAMILY=Arial; FONT-SIZE=16; FONT-STYLE=italic; COLOR="green"} H2 I {FONT-STYLE=normal; COLOR="blue"} </STYLE> <H2>This is a heading with a <I>Normal Blue</I> portion in it </H2> |
Instead of redefining the appearance of all the tags with a given name, you can set the style for a specific tag using the STYLE attribute, as in this code:
<H3 STYLE="FONT-STYLE=bold;COLOR=blue">A blue and bold Level 3 Heading</H3> |
A great feature of style sheets is that they allow you to define new classes of style attributes. This way, you can label an item in the page according to its meaning and specify its appearance elsewhere in the page or (better) in a separate style sheet. This approach is similar to the one you follow when you define a new style in a word processor such as Microsoft Word. For example, suppose that some of your headings are book titles, and you want all book titles in your HTML pages formatted as bold green text. All you have to do is create the booktitle style class, and then apply it when you need it using the CLASS attribute:
<STYLE> .booktitle {FONT-FAMILY=Arial; FONT-STYLE=bold; COLOR="green"} </STYLE> <H3 CLASS=booktitle>Programming Microsoft Visual Basic 6</H3> |
The CLASS attribute really shines when used with the <DIV> and </DIV> tags to apply a particular style class to a portion of the page. (For additional information about the <DIV> tag, see the "Tags" section later in this chapter.)
<STYLE> .listing {FONT-FAMILY=Courier New; FONT-SIZE=12} </STYLE> <DIV CLASS=listing> ' A Visual Basic listing <BR> Dim x As Variant </DIV> |
Finally, here's one way to store a style definition in a separate file, based on the @import directive:
<STYLE> @import URL("http://www.vb2themax.com/stylesheet.css"); </STYLE> |
HTML forms offer a way to let the user enter information in a page. A form can contain controls, including single-line and multiline text boxes, check boxes, radio buttons, push buttons, list boxes, and combo boxes. These controls can't compete with their Visual Basic counterparts, but they're sufficiently powerful for most purposes. All the controls in an HTML form must be enclosed between the <FORM> and </FORM> tags. The <FORM> tag accepts several attributes, the most important of which is NAME, because you need to assign a name to the form if you want to access its controls from script routines. You can place controls outside a form, as, for example, when you plan to process them through scripts and don't plan to post their contents to the Web server.
Most of the controls in a form are inserted using the <INPUT> tag. The TYPE attribute determines the type of control, and the NAME attribute is the name of the control. For example, the following code builds a form with one CheckBox control:
<FORM NAME="formname"> <INPUT TYPE=Checkbox NAME=Shipped CHECKED>The product has been shipped.<BR> </FORM> |
The NAME attribute vaguely corresponds to Visual Basic controls' Name property. The CHECKED attribute displays a mark in the control. The text that follows the > character corresponds to the caption of the control, but as far as HTML is concerned, it's just text that happens to follow the control in the page.
The NAME attribute is more important for RadioButton controls because all the controls with the same name belong to the same group of mutually exclusive choices. You can select one of the controls in the group by adding the CHECKED attribute:
Select the type of malfunction observed:<BR> <INPUT TYPE=Radio NAME="Problem" CHECKED>Wrong Results<BR> <INPUT TYPE=Radio NAME="Problem">Fatal Error<BR> <INPUT TYPE=Radio NAME="Problem">General Protection Fault<BR> |
HTML supports three different types of push buttons: the Submit button, the Reset button, and the generic, programmable button. The first two buttons are similar, differing only for the value of the TYPE attribute:
<INPUT TYPE=Submit VALUE="Submit"> <INPUT TYPE=Reset VALUE="Reset values"> |
In both cases, the VALUE attribute determines the caption of the button. The effect of the Submit button is to send the contents of all the controls on the form to the server. The effect of the Reset button is to clear the contents of all the controls on the form and restore their initial values. The third type of button is used in combination with a script, as I explain in the following section.
HTML forms can contain three types of TextBox controls: the standard single-line control, the control for entering passwords, and the multiline control. The single-line control has a TYPE attribute equal to Text, can contain a VALUE attribute to specify the initial contents of the control, and also supports the SIZE attribute (the width in characters) and the MAXLENGTH attribute (the maximum number of characters):
Enter book title: <BR> <INPUT TYPE=Text NAME="BookTitle" SIZE=40 MAXLENGTH=60 VALUE="Programming Microsoft Visual Basic 6"> |
The Password control is functionally identical to the regular TextBox control and supports the same attributes. It corresponds to a Visual Basic TextBox whose PasswordChar property has been set to an asterisk:
Enter your password: <INPUT TYPE=Password NAME="UserPwd" SIZE=40 MAXLENGTH=60><BR> |
The TextArea control corresponds to a Visual Basic's multiline TextBox control. This control is an exception to the general rule, however, because it uses the <TEXTAREA> tag instead of the <INPUT> tag; you can determine the control's size using the ROWS and COLS attributes, and the initial contents of the control can be inserted before the closing </TEXTAREA> tag:
<TEXTAREA NAME="Comments" ROWS=5 COLS=30 MAXLENGTH=1000> Enter your comments here. </TEXTAREA> |
The text between the <TEXTAREA> and </TEXTAREA> tags is inserted in the control as-is, including carriage returns. If a line is wider than the control's width, the user has to scroll the control to see its rightmost portion.
HTML forms support single-choice and multiple-choice list box controls, which are named Select controls in the HTML jargon. A Select control is defined by means of the <SELECT> and </SELECT> tags, which accept the SIZE attribute for specifying the control's height (in number of rows), and the MULTIPLE attribute if the control accepts multiple choices. Each individual item of the list requires a <OPTION> and </OPTION> tag pair. You can insert the SELECT attribute if the item is initially selected, and a VALUE attribute to specify the string that will be sent to the server when the form is submitted. The following code creates a multiple-choice Select control that's 4 rows tall and whose first item is initially highlighted:
<SELECT NAME="Products" SIZE=4 MULTIPLE> <OPTION SELECTED VALUE=1>Computers</OPTION> <OPTION VALUE=2>Monitors</OPTION> <OPTION VALUE=3>Hard disks</OPTION> <OPTION VALUE=4>CD-ROM drives</OPTION> </SELECT> |
If you omit the MULTIPLE attribute and specify SIZE=1 (or omit it), the Select control turns into a combo box control.
Now that you know how to prepare an HTML page and an HTML form, understanding how scripting fits in is really straightforward. First, you need the <SCRIPT> and </SCRIPT> tags to reserve a section of the HTML document for your script code, as in this code:
<SCRIPT LANGUAGE="VBScript"> ' Your VBScript code goes here. </SCRIPT> |
You can also specify another script language in the LANGUAGE attribute—for example JavaScript—but given the typical reader of this book, all my examples use VBScript.
The VBScript language is an extensive subset of Visual Basic for Applications (VBA) and differs from its more powerful cousin in relatively few features:
NOTE
All the examples in this book are written with VBScript version 3.0. As this book is going to print, VBScript 5 is in public beta. This new version supports classes, property procedures, specific object variables, and the New operator. It also allows sophisticated search and replace capabilities. VBScript 5 will be distributed with Internet Explorer 5.
Most of the time, the code between the <SCRIPT> and </SCRIPT> tags consists of routines that are invoked from elsewhere in the page. Code can be placed outside any routine, however, in which case it's executed immediately after the page has been downloaded from the server but before it's rendered in the browser's window:
<SCRIPT LANGUAGE="VBScript"> MsgBox "About to display a page" </SCRIPT> |
You can also achieve the same result by writing code for the onload event of the Window object, as in this snippet:
<SCRIPT LANGUAGE="VBScript"> ' A variable declared outside any routine is global to the page. Dim loadtime Sub Window_onload() ' Remember when the page has been loaded. loadtime = Now() End Sub </SCRIPT> |
VBScript code can access any control in the form, using the syntax formname.controlname, and can also read and modify attributes of controls using the dot syntax, exactly as in regular Visual Basic. The following code snippet shows you how to assign a string to the VALUE attribute of a TextBox control when the form loads:
<FORM NAME="DataForm"> <INPUT TYPE=Text NAME="UserName" VALUE=""> </FORM> <SCRIPT LANGUAGE="VBScript"> DataForm.UserName.Value = "Francesco" </SCRIPT> |
If you want to access controls on the form when the page loads, the <SCRIPT> tag must follow the <FORM> tag; otherwise, the script attempts to reference a control that doesn't exist yet. You can retrieve the status of a CheckBox control through its Checked property, and the index of the selected item in a Select control using its SelectedIndex property. To check the state of a radio button, you use the following syntax:
If DataForm.RadioButton.Item(0).Checked Then ... |
You frequently use VBScript code to react to events raised by controls. For example, buttons, CheckBox and RadioButton controls raise an onclick event when they're clicked. You can react to such events as you would in standard Visual Basic. The following example uses a TextBox, one Button, and two RadioButton controls; when the push button is clicked, the code converts the TextBox's contents to uppercase or lowercase, according to the RadioButton currently selected:
<FORM NAME="DataForm"> <INPUT TYPE=Text NAME="UserName" VALUE=""><BR> <INPUT TYPE=Radio NAME="Case" CHECKED>Uppercase <INPUT TYPE=Radio NAME="Case">Lowercase<BR> <INPUT TYPE=BUTTON NAME="Convert" VALUE="Convert"> </FORM> <SCRIPT LANGUAGE="VBScript"> Sub Convert_Onclick() If DataForm.Case.Item(0).Checked Then DataForm.UserName.Value = UCase(DataForm.UserName.Value) Else DataForm.UserName.Value = LCase(DataForm.UserName.Value) End If End Sub </SCRIPT> |
Another way to specify which VBScript routine should execute when the user acts on a control is to add an onclick attribute in the definition of the control and set its value to reference the code that has to be executed when the control is clicked. For example, the following code defines two RadioButtons that, when clicked, modify the contents of a TextBox control:
<FORM NAME="UserData"> <INPUT TYPE=Text NAME="UserName" VALUE=""><BR> <INPUT TYPE=Radio NAME="Case" onClick="Convert(0)" CHECKED>Uppercase<BR> <INPUT TYPE=Radio NAME="Case" onClick="Convert(1)">Lowercase<BR> </FORM> <SCRIPT LANGUAGE="VBScript"> Sub Convert(index) If index = 0 Then UserData.Username.Value = UCase(UserData.Username.Value) Else UserData.Username.Value = LCase(UserData.Username.Value) End If End Sub </SCRIPT> |
Usually, the value of the onclick attribute is the name of the procedure that must be called, together with its arguments (index, in this case), but in general it can be any valid piece of VBScript code.
TextBox, TextArea, and Select controls raise an onchange event when the user types something in them or selects a new item.
Scripts are often used to add items to a Select control at run time. The sequence of actions necessary for reaching this goal will probably seem contorted to a Visual Basic programmer: You must use the CreateElement method of the Document object, set its Text and Value properties, and finally add it to the Options collection of the Select control. The following example creates a form with a Select control and a push button. Initially, the Select control contains only one item, but you can add two more items by clicking on the button:
<FORM NAME="UserForm"> <SELECT NAME="Countries" SIZE=1> <OPTION VALUE=1>US</OPTION> </SELECT> <INPUT TYPE=BUTTON NAME="AddCountries" VALUE="Add Countries"> </FORM> <SCRIPT LANGUAGE="VBScript"> Sub AddCountries_onclick() Dim e Set e = Document.createElement("OPTION") e.Text = "Italy" e.Value = 2 Userform.Countries.Options.Add e Set e = Document.createElement("OPTION") e.Text = "Germany" e.Value = 3 Userform.Countries.Options.Add e End Sub </SCRIPT> |
VBScript lets you generate a new HTML page on the fly, using the Write method of the Document object. I explain the Document object (and all the other objects available to HTML programmers) later in this chapter, but a simple example can give you a taste of what you can do:
<FORM NAME="UserData"> <INPUT TYPE=Text NAME="Rows" VALUE="10"> <INPUT TYPE=Text NAME="Cols" VALUE="10"><BR> <INPUT TYPE=Button NAME="Generate" VALUE="Generate Table"> </FORM> <SCRIPT LANGUAGE="VBScript"> Sub Generate_onclick() Dim rows, cols ' We need to store these values in variables before the form is ' destroyed when a new document is created. rows = UserData.Rows.Value cols = UserData.Cols.Value Document.Open Document.Write "<H1>Multiplication Table</H1>" Document.Write "<TABLE BORDER=1>" For r = 1 to rows Document.Write "<TR>" For c = 1 to cols Document.Write "<TD> " & (r*c) & " </TD>" Next Document.Write "</TR>" Next Document.Write "</TABLE>" End Sub </SCRIPT> |
This code programmatically creates a new HTML page, which contains a multiplication table whose size is specified by the user in two text box controls. (See Figure 19-3.) As soon you issue the Open method of the Document object, the UserData form doesn't exist any longer, so you need to cache the values of those text box controls in the rows and cols local variables before you create the new page.
Figure 19-3. An HTML page that dynamically creates a multiplication table with a given number of rows and columns.
This concludes our quick course on HTML and VBScript. Now you're ready to move on to Dynamic HTML and appreciate its great flexibility and increased power.